package com.artezio.buyndrive.web;

import com.artezio.buyndrive.domain.Admin;
import com.artezio.buyndrive.service.UserService;
import com.artezio.buyndrive.service.impl.CapchaServiceImpl;
import com.artezio.buyndrive.service.impl.MD5ServiceImpl;
import com.artezio.buyndrive.service.impl.MailServiceImpj;
import com.artezio.buyndrive.validator.RegistrationValidator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * User: spolyakov
 * Date: 23.07.12
 * Time: 15:19
 */

@Controller
public class RegistrationController {

    protected final Log logger = LogFactory.getLog(RegistrationController.class);

    @Autowired
    private UserService userService;

    @Autowired(required = true)
    private RegistrationValidator registrationValidator;

    @RequestMapping("/registration/takeReg")
    public ModelAndView takeReg(Model model,
                                HttpServletRequest servletRequest, HttpSession session) {
        logger.info("/takeReg");

        //для доступа к странице регистрации
        model.addAttribute("user", new Admin());
        //будущий зарегистрированный пользователь.
        model.addAttribute("new_user", new Admin());

        return new ModelAndView("registerUser");
    }

    @RequestMapping(value = "/registration/makeReg", method = RequestMethod.POST)
    public String makeReg(HttpServletRequest servletRequest, HttpSession httpSession,
                          Model model, @ModelAttribute("new_user") Admin admin,
                          BindingResult result) {
        logger.info("Trying to makeReg...");

        String confPass = servletRequest.getParameter("confPassword");

        CapchaServiceImpl capcha = new CapchaServiceImpl();

        registrationValidator.validate(admin, result);
        registrationValidator.confirmPass(admin, result, confPass);

        if (result.hasErrors()) {
            logger.error("Adding error!");

            model.addAttribute("user", new Admin());
            return "registerUser";
        }

        /* проверка капчи */


        if (httpSession.getAttribute("capcha_right") == null) {
            httpSession.setAttribute("capcha_right", false);
        }

        if (httpSession.getAttribute("capcha_right").equals(Boolean.FALSE)) {

            if (capcha.isHuman(servletRequest)) {
                System.out.println("[CAPTCHA] Answer was entered correctly!");
                httpSession.setAttribute("capcha_right", true);
            } else {
                System.out.println("[CAPTCHA] Answer is wrong!");
                model.addAttribute("user", new Admin());

                return "registerUser";
            }
        }

        /* конец проверки капчи */


        //test

        try {

            MailServiceImpj mailServiceImpj = new MailServiceImpj();
            MD5ServiceImpl md5Service = new MD5ServiceImpl();

            String message = "Для продолжения регистрации пройдтите по ссылке ниже:\n"
                    + "http://localhost:8082/buy-n-drive/registration/continue"
                    + "?email=" + admin.getEmail()
                    + "&code="
                    + md5Service.getMD5(admin.getEmail());

            mailServiceImpj.send(admin.getEmail(), "CONTINUE REGISTRATION", message);

            System.out.println(message);

        } catch (Exception e) {
            logger.error(e);
        }

        //end test

        admin.setIsActive(false);

        //Установка роли пользователя. (Не админа)
        admin.setRole(1);

        userService.saveOrUpdate(admin);

        return "redirect:/";
    }

    @RequestMapping(value = "/registration/continue", method = RequestMethod.GET)
    public String check(HttpServletRequest servletRequest, HttpSession httpSession) {

        try {
            String email = servletRequest.getParameter("email");
            String pass = servletRequest.getParameter("code");

            Admin user = (Admin) userService.get(email);

        MD5ServiceImpl md5Service = new MD5ServiceImpl();
        String checkSum = md5Service.getMD5(user.getEmail());

        if (checkSum.equals(pass)) {
            user.setIsActive(true);
            userService.saveOrUpdate(user);

            httpSession.setAttribute("user", user);

            System.out.println("User activates!");

            return "redirect:/personal";
        } else {
            System.out.println("Activation error!");
            return "redirect:/";
        }

        } catch (Exception e) {
            logger.error(e);
            return "redirect:/";
        }
    }

}
